import produce from 'immer';

/**
 * 数组 “数据映射”
 */
const dataMapping = (
  records = [
    {
      name: '文件夹1',
      type: '文件夹',
      children: [
        {
          name: '文件1',
          type: '文件',
        },
      ],
    },
    {
      name: '文件3',
      type: '文件',
    },
  ],
  mapping = {
    name: 'name_x',
    children: 'children_x',
  },
) =>
  records.map(record =>
    produce(record, draftState => {
      Object.keys(mapping).forEach(key => {
        const newKey = mapping[key];
        const newValue = draftState[key];
        if (newValue) {
          if (Array.isArray(newValue)) {
            draftState[newKey] = dataMapping(newValue, mapping); // 处理数组
          } else {
            draftState[newKey] = newValue; // 处理其他
          }
        }
      });
      return draftState;
    }),
  );

/**
 * 数组去重
 */
function removeDuplicates(
  array = [],
  funcFindIndex = (rawArray = [], item = '') => {
    return rawArray.indexOf(item);
  },
) {
  return array.filter((item, index) => funcFindIndex(array, item) === index);
}

/**
 * 增强 “逻辑或”
 */
function logicalOR(array = []) {
  return array.find(item => item !== undefined && item !== null);
}

/**
 * 文件下载
 */
const download = (fileName, bytes) => {
  const link = document.createElement('a');
  const blob = new Blob([bytes]);
  link.download = fileName;
  link.href = URL.createObjectURL(blob);
  link.click();
  URL.revokeObjectURL(blob);
};

/**
 * 获取文件类型
 */
const getFileType = fileName => {
  const splits = fileName.split('.');
  const fileType = splits[splits.length - 1];
  if (fileType && fileType.includes('?')) {
    return fileType.split('?')[0];
  }
  if (fileType && fileType.includes('#')) {
    return fileType.split('#')[0];
  }
  return fileType;
};

/**
 * 同步执行 “Promise 函数”
 */
const syncExecute = async (promiseFunctions = [], callback) => {
  for (const promiseFunction of promiseFunctions) {
    const response = await promiseFunction(); // eslint-disable-line
    if (callback) {
      callback(response);
    }
  }
};

export { dataMapping, removeDuplicates, logicalOR, download, getFileType, syncExecute };
